package com.nakanomay.zkcase1;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @author nakano_may丶
 * @date 2023/4/17
 * @Version 1.0
 * @description zk服务端代码
 */
public class DistributeServer
{
    private String connectString = "172.16.102.100:2181,172.16.102.135:2181,172.16.102.136:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zk = null;

    public static void main(String[] args) throws Exception
    {
        DistributeServer server = new DistributeServer();

        // 1 获取zk连接
        server.getConnect();

        // 2 注册服务器到zk集群
        server.registry(args[0]);

        // 3 启动业务逻辑（睡觉）
        server.business();

    }

    private void business() throws InterruptedException
    {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void registry(String hostname) throws Exception
    {
        String create = zk.create("/servers/" + hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        System.out.println(hostname + " is online");
    }

    private void getConnect() throws IOException
    {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher()
        {
            @Override
            public void process(WatchedEvent event)
            {

            }
        });
    }
}
